package tech.eyao.hs60x.utils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 全局公共线程池
 * @author hejian  
 * @date 2017年10月13日
 */
public class ThreadUtil {

    /** 线程池大小 **/
    private static final int DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();

    private static class SingletonHolder {
        private SingletonHolder() {}
        
        private static final ExecutorService DEFAULT_THREAD_POOL_INSTANCE = newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE, "ThreadPoolHs60XHolder-fixed-");
    }

    private ThreadUtil() {}

    public static final ExecutorService getDefaultFixedThreadPool() {
        return SingletonHolder.DEFAULT_THREAD_POOL_INSTANCE;
    }
    
    public static void execute(Runnable command) {
        getDefaultFixedThreadPool().execute(command);
    }
    
    public static Future<?> submit(Callable<?> command) {
        return getDefaultFixedThreadPool().submit(command);
    }
    
    public static ExecutorService newFixedThreadPool(int poolSize, String prefix) {
        return Executors.newFixedThreadPool(poolSize, createNamedThreadFactory(prefix));
    }

    /**
     * 创建一个带前缀名称的线程工厂
     * 
     * @param prefix 线程名称前缀
     */
    public static ThreadFactory createNamedThreadFactory(String prefix) {
        return new ThreadFactory() {

            private final AtomicLong tNum = new AtomicLong(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, prefix + tNum.getAndIncrement());
            }
        };
    }
}
